<template>
  <div class="container" >
    <a-tree-select
      style="width: 100%"
      :value="value"
      :placeholder="orgName"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      allow-clear
      tree-default-expand-all
      @change="onTreeChange"
    >
      <a-tree-select-node
        :key="item._id"
        :value="`${item.subOrgName}#`"
        :title="item.subOrgName"
        v-for="item in peopleTreeList"
      >
        <a-tree-select-node
          :key="element.title"
          :value="`${item.subOrgName}:${element.title}`"
          :title="element.title"
          v-for="element in item.title"
        >
        </a-tree-select-node>
      </a-tree-select-node>
    </a-tree-select>

    <batchAddTeacher :visible.sync="bulkImport_visible"></batchAddTeacher>
    <a-modal v-model="editModal_visible" title="编辑" @ok="handleSubmit" @cancel="editCancel">
      <a-form
        :model="userInformation"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-model-item label="工号">
          <p>{{ userInformation.user_id }}</p>
        </a-form-model-item>
        <a-form-model-item label="姓名">
          <a-input v-model="userInformation.name" />
        </a-form-model-item>
        <a-form-model-item label="学院">
          <a-select @change="handleSelectChange" v-model="subOrg_name">
            <a-select-option
              v-for="item in colleges"
              :key="item._id"
              :value="item.subOrgName"
            >
              {{ item.subOrgName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="专业">
          <a-select v-model="userInformation.major_name">
            <a-select-option
              v-for="item in major_names"
              :key="item._id"
              :value="item.majorName"
            >
              {{ item.majorName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="状态">
          <a-switch
            v-model="userInformation.active"
            checked-children="已启用"
            un-checked-children="已禁用"
            @change="onChange"
          />
        </a-form-model-item>
        <a-form-model-item label="职称">
          <!-- <a-input v-model="form.title" /> -->
          <a-select @change="handleSelectChange" v-model="userInformation.title">
            <a-select-option
              v-for="item in titles"
              :key="item._id"
              :value="item.title"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="身份">
          <!-- <a-input v-model="form.title" /> -->
        <a-select @change="handleSelectChange" v-model="userInformation.role">
            <a-select-option
              v-for="item in roles"
              :key="item._id"
              :value="item.role"
            >
              {{ item.role }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form>
    </a-modal>


    <a-modal v-model="addModal_visible" title="添加" @ok="addSubmit" @cancel="addCancel">
      <a-form
        :model="userInformation"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-model-item label="工号">
          <a-input v-model="userInformation.user_id" />
        </a-form-model-item>
        <a-form-model-item label="姓名">
          <a-input v-model="userInformation.name" />
        </a-form-model-item>
        <a-form-model-item label="email">
          <a-input v-model="userInformation.email" />
        </a-form-model-item>
        <a-form-model-item label="学院">
          <a-select @change="handleSelectChange" v-model="subOrg_name">
            <a-select-option
              v-for="item in colleges"
              :key="item._id"
              :value="item.subOrgName"
            >
              {{ item.subOrgName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="专业">
          <a-select v-model="userInformation.major_name">
            <a-select-option
              v-for="item in major_names"
              :key="item._id"
              :value="item.majorName"
            >
              {{ item.majorName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="状态">
          <a-switch
            v-model="userInformation.active"
            checked-children="已启用"
            un-checked-children="已禁用"
            @change="onChange"
          />
        </a-form-model-item>
        <a-form-model-item label="职称">
          <!-- <a-input v-model="form.title" /> -->
          <a-select @change="handleSelectChange" v-model="userInformation.title">
            <a-select-option
              v-for="item in titles"
              :key="item._id"
              :value="item.title"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="身份">
          <!-- <a-input v-model="form.title" /> -->
        <a-select @change="handleSelectChange" v-model="userInformation.role">
            <a-select-option
              v-for="item in roles"
              :key="item._id"
              :value="item.role"
            >
              {{ item.role }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form>
    </a-modal>

    <!-- <a-row> -->
    <div>
      <!-- <a-row> -->
      <div class="btn-area" >
          <div class="search" >
            <a-input-search  @search="searchAll"  placeholder="请输入工号(学号)/姓名" enter-button />
          </div>     
        <a-col class="btns">  
          <a-button type="primary" @click="addTeacher"
            >添加</a-button
          >
          <a-button type="primary" @click="changeStatus(selectedTeachers, 0)"
            >启用</a-button
          >
          <a-button type="danger" @click="changeStatus(selectedTeachers, 1)"
            >禁用</a-button
          >
          <a-button type="primary" @click="bulkImport_visible = true"
            >批量导入</a-button
          >
          <a-button type="danger" @click="showDeleteConfirm(selectedTeachers)"
            >批量删除</a-button
          >
        </a-col>
      </div>
      <!-- </a-row> -->
      <a-row >
        <a-spin :spinning="tableSpinningStatus">
          <a-table
            size="small"
            :key="tableIndex"
            rowKey="_id"
            :pagination="{
              total: teacherList.length,
              pageSizeOptions: pageSize,
              defaultPageSize: 20,
              'hide-on-single-page': true,
            }"
            :bordered="true"
            :row-selection="{
              selectedRowKeys: selectedTeachers,
              onChange: onRowChange,
            }"
            :columns="columns"
            :data-source="teacherList"
          >
            <a-icon
              slot="filterIcon"
              slot-scope="filtered"
              type="search"
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
            <template
              slot="customRender"
              slot-scope="text, record, index, column"
            >
              <span v-if="searchText && searchedColumn === column.dataIndex">
                <template
                  v-for="(fragment, i) in text
                    .toString()
                    .split(
                      new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i')
                    )"
                >
                  <mark
                    v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                    :key="i"
                    class="highlight"
                    >{{ fragment }}</mark
                  >
                  <template v-else>{{ fragment }}</template>
                </template>
              </span>
              <template v-else>
                {{ text }}
              </template>
            </template>
            <template #operation="record">
              <a-button type="link" @click="editTeacher(record)">编辑</a-button>
              <a-button type="link" @click="resetPassword(record)"
                >重置密码</a-button
              >
              <a-button type="link" @click="deleteTeacher(record)"
                >删除</a-button
              >
            </template>
            <template #state="text">
              <a-tag color="#388e3c" v-if="text"> 已启用</a-tag>
              <a-tag color="#ff5252" v-else> 已禁用</a-tag>
            </template>
          </a-table>
        </a-spin>
      </a-row>
    </div>
    <!-- </a-row> -->
  </div>
</template>

<script>
import batchAddTeacher from "./BatchAddTeacher.vue";
import axiosInstance from "@/utils/axios";
import { mapState } from "vuex";
export default {
  components: {
    batchAddTeacher,
  },
  data() {
    const columns = [
      {
        title: "工号（学号）",
        dataIndex: "user_id",
        align: "center",
        scopedSlots: {
          filterDropdown: "filterDropdown",
          filterIcon: "filterIcon",
          customRender: "customRender",
        },
        onFilter: (value, record) =>
          record.user_id.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
          if (visible) {
            setTimeout(() => {
              // 点击获取焦点，且进入微任务序列
              this.searchInput.focus();
            }, 0);
          }
        },
      },
      {
        title: "姓名",
        dataIndex: "name",
        align: "center",
      },
      {
        title: "所属学院",
        dataIndex: "subOrg_name",
        align: "center",
      },
      {
        title: "专业",
        dataIndex: "major_name",
        align: "center",
      },
      {
        title: "职称",
        dataIndex: "title",
        align: "center",
      },
      {
        title: "身份",
        dataIndex: "role",
        align: "center",
      },
      {
        title: "状态",
        dataIndex: "active",
        align: "center",
        scopedSlots: { customRender: "state" },
      },
      {
        title: "操作",
        scopedSlots: { customRender: "operation" },
        align: "center",
      },
    ];
    return {
      // 搜索内容
      searchText: "",
      searchInput: null,
      searchedColumn: "",
      //
      tableSpinningStatus: false,
      value: undefined,
      addModal_visible: false,
      editModal_visible: false,
      bulkImport_visible: false,
      searchContent: "",
      upload_url: "",
      tableIndex: 0,
      pageSize: ["10", "20", "30", "50", "100"],
      userInformation: {
        user_id: "",
        name: "",
        org_name:this.orgName,
        subOrg_name: "",
        major_name: "",
        title: "",
        active: undefined,
        email:"",
        role:"",
      },
      user_id: "",
      columns,
      selectedTeachers: [],
      vall:"",
      //学院列表
      titles: [
        { _id: "1", title: "教授", },
        { _id: "2", title: "副教授", },
        { _id: "3", title: "讲师" , },
        { _id: "4", title: "学生" , },
        { _id: "5", title: "其他" , },
      ],
      roles: [
        { _id: "1", role: "老师", },
        { _id: "2", role: "学生", },
        { _id: "3", role: "督导" , },
        { _id: "5", role: "其他" , },
      ],
      subOrg_name: "",
      colleges: [],
      major_names: [],
      teacherList: [],
      teacherLists: [],
      teacherListss: [],
      peopleTreeList: [],
    };
  },
  computed: {
    ...mapState({
      orgName: (state) => state.public.orgName,
      oid: (state) => state.public.oid,
      role: (state) => state.public.role,
    }),
  },
  mounted() {
    // 获取学院名
    this.getSubOrgsName();
    this.getAllTeacherList();
    // this.getSubOrgsName();
    this.getTreeList();

  },
  watch: {
    tableIndex() {
      this.getTeacherList();
    },
    subOrg_name(val) {
      // 根据学院找到专业赋值
      this.userInformation.subOrg_name = val;
      // console.log(val)
      this.getmajors(val);
    },
  },
  methods: {
    goto(){
      this.goooo = true;
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
    },
    async getSubOrgsName() {
      // 获取学院名
      const orgId = this.oid;
      const url = "/pc/v1/organizations/" + orgId + "/suborgs";
      try {
        const { data } = await axiosInstance.get(url);
        this.colleges = data.subOrgs;
      } catch (err) {
        console.log(err);
      }
    },
    async getmajors(queryString) {
      // 按获取专业
      // console.log(queryString)
      // console.log(this.orgName
      const url =
        "/pc/v1/organizations/" + this.orgName + "/suborgs/" + queryString;
      try {
        const { data } = await axiosInstance.get(url);
        // console.log(data)
        this.major_names = data.majors;
        // console.log(data.data.majors);
      } catch (err) {
        console.log(err);
      }
    },
    //连接后台获取成功之后记得更改前台数据
    //操作成功或失败弹出提示
    handleUpdateClick() {
      this.tableIndex += 1;
    },
    async getTreeList() {
      try {
        // console.log(this.orgName);
        // const url =
        //   "/pc/v1/users/getUsersBySubOrgAndSortByTitle?org_name=" + this.orgName;
        const url = "/pc/v1/organizations/" + this.oid + "/tree";
        const { data } = await axiosInstance(url);
        this.peopleTreeList = data.tree;
        this.peopleTreeList.forEach((tree) => {
          tree.title = this.titles;
        });
        // console.log(data);
      } catch (err) {
        console.log(err);
      }
    },
    async getTeacherList(payload) {
      // const queryObject = {
      //   org_name: this.orgName,
      //   role: "teacher",
      // };
      let queryObject = payload;
      let queryString = "";
      if (!queryObject) {
        return;
      }
      Object.keys(queryObject).forEach((key) => {
        queryString += key + "=" + queryObject[key] + "&";
      });
      queryString = "?" + queryString.slice(0, -1);
      const url = "/pc/v1/users/multipleUsers" + queryString;
      try {
        const { data } = await axiosInstance.get(url);
        // 管理员不允许修改管理员
        // 此处应该在后端修改，但由于一期快结束，所以不能改变太大。
        data.teachers = data.teachers.filter((user) => {
          return user.role != "orgAdmin";
        });
        this.teacherList = data.teachers;
      } catch (err) {
        console.log(err);
      }
    },
    async getAllTeacherList() {
      try {
        let queryString = `?org_name=${this.orgName}`;
        const url = "/pc/v1/users" + queryString;
        this.tableSpinningStatus = true;
        const { data } = await axiosInstance.get(url);
        // 管理员不允许修改管理员
        // 此处应该在后端修改，但由于一期快结束，所以不能改变太大。
        data.users = data.users.filter((user) => {
          return user.role != "orgAdmin";
        });
        for(var i=0;i<data.users.length;i++){
          if(data.users[i].role == "student"){
            data.users[i].role = "学生";
          } 
          else if(data.users[i].role == "teacher"){
            data.users[i].role = "老师";
          } 
            else if(data.users[i].role == "patrol"){
            data.users[i].role = "督导";
          } 
        }
        this.teacherList = data.users;
        this.teacherLists = data.users;
        this.tableSpinningStatus = false;
      } catch (err) {
        console.log(err);
        this.tableSpinningStatus = false;
      }
    },
    //table options
    onRowChange(keys) {
      this.selectedTeachers = keys;
      console.log(this.selectedTeachers);
    },
    searchAll(val){    
      this.teacherListss = this.teacherLists;
      if (val == ""){
        this.getAllTeacherList();
      }
      else{      
        this.teacherListss =  this.teacherListss.filter((user) => {
          return user.user_id.includes(val) || user.name.includes(val);
        });
      }
      this.teacherList = this.teacherListss;
    },
    addTeacher() {
      this.addModal_visible = true;
      this.userInformation.name = "";
      this.userInformation.user_id = "";
      this.userInformation.title = "";
      this.userInformation.email = "";
      this.userInformation.major_name = "";
      this.userInformation.role = "";
      this.userInformation.active = undefined;
    },
    //row options
    editTeacher(record) {
      this.editModal_visible = true;
      this.userInformation = record;
      this.subOrg_name = record.subOrg_name;
      this.user_id = record._id;
    },
    resetPassword(record) {
      // console.log(record);
    },
    handleSubmit() {
      let url = `pc/v1/users/${this.user_id}`;
      let that = this;
      if ( this.userInformation.title == "教授") {
        this.userInformation.title = "professor";
      }
      else if (this.userInformation.title == "副教授"){
        this.userInformation.title = "vice-professor";
      }
      else if (this.userInformation.title == "讲师"){
        this.userInformation.title = "lecturer";
      }
      else if (this.userInformation.title == "学生"){
        this.userInformation.title = "student";
      }
      if (this.userInformation.role == "学生"){
        this.userInformation.role = "student";
      }
      else if (this.userInformation.role == "老师"){
        this.userInformation.role = "teacher";
      }
      else if (this.userInformation.role == "督导"){
        this.userInformation.role = "patrol";
      }
      console.log(this.userInformation.role);
      axiosInstance.patch(url, this.userInformation).then(
        function (res) {
          that.$message.success("编辑成功");
        },
        function (err) {
          console.log(err);
          that.$message.error("编辑失败");
        }
      );
      if ( this.userInformation.title == "professor") {
        this.userInformation.title = "教授";
      }
      else if (this.userInformation.title == "vice-professor"){
        this.userInformation.title = "副教授";
      }
      else if (this.userInformation.title == "lecturer"){
        this.userInformation.title = "讲师";
      }
      else if (this.userInformation.title == "student"){
        this.userInformation.title = "学生";
      }
      else if (this.userInformation.role == "student"){
        this.userInformation.role = "学生";
      }
      else if (this.userInformation.role == "teacher"){
        this.userInformation.role = "老师";
      }
      else if (this.userInformation.role == "patrol"){
        this.userInformation.role = "督导";
      }
      //刷新界面
      this.getAllTeacherList();
      this.editModal_visible = false;
      },
    editCancel(){
      this.getAllTeacherList();
    },
    async addSubmit() {
      this.userInformation.org_name = this.orgName;
      if ( this.userInformation.title == "教授") {
        this.userInformation.title = "professor";
      }
      else if (this.userInformation.title == "副教授"){
        this.userInformation.title = "vice-professor";
      }
      else if (this.userInformation.title == "讲师"){
        this.userInformation.title = "lecturer";
      }
      else if (this.userInformation.title == "学生"){
        this.userInformation.title = "student";
      }
      if (this.userInformation.role == "学生"){
        this.userInformation.role = "student";
      }
      else if (this.userInformation.role == "老师"){
        this.userInformation.role = "teacher";
      }
      else if (this.userInformation.role == "督导"){
        this.userInformation.role = "patrol";
      }
      try {
        const url = `/pc/v1/users/multipleUsers`;
        const data = await axiosInstance.post(url, [this.userInformation]);
        this.$message.info("添加成功");
      } catch (err) {
        this.$message.error("添加失败");
        console.log(err);
      }
      if ( this.userInformation.title == "professor") {
        this.userInformation.title = "教授";
      }
      else if (this.userInformation.title == "vice-professor"){
        this.userInformation.title = "副教授";
      }
      else if (this.userInformation.title == "lecturer"){
        this.userInformation.title = "讲师";
      }
      else if (this.userInformation.title == "student"){
        this.userInformation.title = "学生";
      }
      else if (this.userInformation.title == "patrol"){
        this.userInformation.title = "巡课";
      }
      else if (this.userInformation.role == "student"){
        this.userInformation.role = "学生";
      }
      else if (this.userInformation.role == "teacher"){
        this.userInformation.role = "老师";
      }
      else if (this.userInformation.role == "patrol"){
        this.userInformation.role = "督导";
      }
      this.getAllTeacherList();
      this.addModal_visible = false;
    },
    addCancel(){
      this.getAllTeacherList();
    },
    handleSelectChange(value) {
      console.log(value);
    },
    handleCancel(e) {
      this.$message.warning("取消修改");
      this.handleUpdateClick();
    },
    onChange(checked) {
      console.log(`a-switch to ${checked}`);
    },
    changeStatus(changeList, e) {
      let that = this;
      changeList.length == 0
        ? this.$message.info("请选中要操作的项")
        : this.$confirm({
            title: "确认更改吗",
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            onOk() {
              if (e === 0) {
                changeList.forEach(async (item) => {
                  let url = `pc/v1/users/${item}`;
                  // that.$store.commit("admin/getUserState", item);
                  let data = {
                    active: true,
                  };
                  try {
                    await axiosInstance.patch(url, data);
                    // 刷新
                    that.$message.success("启用成功");
                    that.getAllTeacherList();
                  } catch (err) {
                    console.log(err);
                    that.$message.error("启用失败");
                  }
                });
              } else if (e === 1) {
                changeList.forEach(async (item) => {
                  let url = `pc/v1/users/${item}`;
                  // that.$store.commit("admin/getUserState", item);
                  let data = {
                    active: false,
                  };
                  try {
                    await axiosInstance.patch(url, data);
                    that.$message.success("禁用成功");
                    // 刷新数据
                    that.getAllTeacherList();
                  } catch (err) {
                    console.log(err);
                    that.$message.error("禁用失败");
                  }
                });
              }
              that.handleUpdateClick();
              that.getTeacherList();
            },
            onCancel() {
              console.log("Cancel");
              that.$message.warning("操作取消");
            },
          });
    },
    deleteTeacher(record) {
      this.showDeleteConfirm(record._id);
      console.log(record._id);
    },
    showDeleteConfirm(userId) {
      var that = this;
      userId.length == 0
        ? this.$message.info("请选中要删除的项")
        : this.$confirm({
            title: "确认删除吗",
            content: "数据删除后不可恢复",
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            async onOk() {
              const url = "/pc/v1/user/" + userId;
              try {
                await axiosInstance.delete(url);
                that.$message.info("删除成功！");
              } catch (err) {
                console.log(err);
                that.$message.error("删除失败，请重试！");
              }
            },
          });
    },

    //bulk import
    download() {
      let url = ""; //输入模板下载url
      window.open(url);
    },
    //上传批量导入表格
    handleChange(info) {
      this.upload_url = ""; //上传地址
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
    },
    //点击上传文件
    bulkimportSubmit() {},
    async onTreeChange(value, label) {
      this.flag = value;
      if (this.flag.slice(-1) == "#") {
        let payload = {};
        let temp = this.flag.slice(0, -1);
        payload = { subOrg_name: temp, org_name: this.orgName };
        console.log(
          "🚀 ~ file: Teacher.vue ~ line 496 ~ onTreeChange ~ payload",
          payload
        );
        this.getTeacherList(payload);
      } else {
        let payload = {};
        let dataArray = this.flag.split(":");
        // console.log(dataArray);
        let secString = "";
        let role = "teacher";
        switch (dataArray[1]) {
          case "教授":
            secString = "professor";
            break;
          case "副教授":
            secString = "vice-professor";
            break;
          case "讲师":
            secString = "lecturer";
            break;
          case "学生":
            role = "student";
            secString = "student";
            break;
          default:
            break;
        }
        payload = {
          org_name: this.orgName,
          subOrg_name: dataArray[0],
          title: secString,
          role: role,
        };
        // console.log(payload);
        this.getTeacherList(payload);
      }
      this.value = label;
    },
  },
};
</script>

<style scoped>
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
.container {
  padding: 10px;
  height: 100%;
}

.btn-area {
  width: 100%;
  padding: 15px 0;
  display: flex;
  justify-content: space-between;
}

.btns .ant-btn {
  margin: 0 5px;
}
::v-deep .ant-table-row {
  padding-top: 0;
}
::v-deep .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0;
}
::v-deep
  .ant-table-small
  > .ant-table-content
  > .ant-table-body
  > table
  > .ant-table-tbody
  > tr
  > td {
  padding: 5px 5px;
}
.search{
    float: left;
}
</style>
